#include <jni.h>
#include <string>
#include "jlog.h"
#include "audio/audioutils.h"

extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_jay_codec_CodecUtils_configuration(JNIEnv *env, jobject thiz) {
    char info[10000] = {0};
    sprintf(info, "%s\n", avcodec_configuration());
    return env->NewStringUTF(info);
}

extern "C"
JNIEXPORT jobject JNICALL
Java_com_jay_codec_CodecUtils_getAudioInfo(JNIEnv *env, jobject thiz, jstring path) {
    const char *inputPath = env->GetStringUTFChars(path, NULL);

    LOGD("获取音频开始");

    AVFormatContext *formatContext = avformat_alloc_context();
    if (avformat_open_input(&formatContext, inputPath, NULL, NULL) != 0) {
        LOGE("无法打开文件 %s", inputPath);
        return NULL;
    }

    LOGD("获取音频 open input 成功");
    int ret = avformat_find_stream_info(formatContext, NULL);
    if (ret < 0) {
        LOGE("获取音频 find stream 失败 %s %i", inputPath, ret);
        return NULL;
    }

    LOGD("获取音频 find stream 成功");

    LOGD("Duration          %ld", formatContext->duration);
    LOGD("BitRate           %ld", formatContext->bit_rate);
    for (int i = 0; i < formatContext->nb_streams; i++) {
        if (formatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            LOGD("找到音频流");
            LOGD("TrackIndex        %i", i);

            LOGD("CodecType         %u",    formatContext->streams[i]->codecpar->codec_type);
            LOGD("CodecId           %u",    formatContext->streams[i]->codecpar->codec_id);

            LOGD("Duration          %ld",   formatContext->streams[i]->duration);

            LOGD("CodecTag          %u",    formatContext->streams[i]->codecpar->codec_tag);
            LOGD("BitRate           %ld",   formatContext->streams[i]->codecpar->bit_rate);

            LOGD("Channels          %i",    formatContext->streams[i]->codecpar->channels);
            LOGD("ChannelLayout     %ld",   formatContext->streams[i]->codecpar->channel_layout);

            LOGD("SampleRate        %i",   formatContext->streams[i]->codecpar->sample_rate);
            LOGD("BitsPerRawSample  %i",   formatContext->streams[i]->codecpar->bits_per_raw_sample);
        }
    }

    env->ReleaseStringUTFChars(path, inputPath);

    return NULL;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_jay_codec_CodecUtils_flacToMp3(JNIEnv *env, jobject thiz, jstring source_path,
                                        jstring dest_path) {

}
extern "C"
JNIEXPORT jint JNICALL
Java_com_jay_codec_CodecUtils_mp3ToFlac(JNIEnv *env, jobject thiz, jstring source_path,
                                        jstring dest_path) {
    const char* sourcePath = env->GetStringUTFChars(source_path,NULL);
    const char* destPath = env->GetStringUTFChars(dest_path,NULL);

    int ret = mp3ToFlac(sourcePath, destPath);

    env->ReleaseStringUTFChars(source_path, sourcePath);
    env->ReleaseStringUTFChars(dest_path, destPath);
    return ret;
}